package com.whpost.service.tools;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.SortedMap;
import java.util.TreeMap;

public class ReaderXmlForDOM {   
       
    @SuppressWarnings("finally")
	public static String parse(String protocolXML,String zdm) {   
            String fhz="";
        try {   
             DocumentBuilderFactory factory = DocumentBuilderFactory   
                     .newInstance();   
             DocumentBuilder builder = factory.newDocumentBuilder();   
             Document doc = builder   
                     .parse(new InputSource(new StringReader(protocolXML)));   
  
             Element root = doc.getDocumentElement();   
             NodeList books = root.getChildNodes();   
            if (books != null) {   
                for (int i = 0; i < books.getLength(); i++) {   
                     Node book = books.item(i);   
                     if (zdm.equals(book.getNodeName())) fhz=book.getFirstChild().getNodeValue();
                     //System.out.println("节点=" + book.getNodeName() + "\ttext="  
                            // + book.getFirstChild().getNodeValue());   
                 }   
             }   
         } catch (Exception e) {   
             e.printStackTrace();   
         }   
        finally{
        	return fhz;
        }
     }   
    @SuppressWarnings("finally")
	public static SortedMap<Object, Object> parse(String protocolXML) {   
            String fhz="";
            SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
        try {   
             DocumentBuilderFactory factory = DocumentBuilderFactory   
                     .newInstance();   
             DocumentBuilder builder = factory.newDocumentBuilder();   
             Document doc = builder   
                     .parse(new InputSource(new StringReader(protocolXML)));   
  
             Element root = doc.getDocumentElement();   
             NodeList books = root.getChildNodes();   
            if (books != null) {   
                for (int i = 0; i < books.getLength(); i++) {   
                     Node book = books.item(i);  
                     if (book.getNodeName().equals("sign")) continue;
                     parameters.put(book.getNodeName(), book.getFirstChild().getNodeValue());
                     //if (zdm.equals(book.getNodeName())) fhz=book.getFirstChild().getNodeValue();
                     //System.out.println("节点=" + book.getNodeName() + "\ttext="  
                            // + book.getFirstChild().getNodeValue());   
                 }   
             }   
         } catch (Exception e) {   
             e.printStackTrace();   
         }   
        finally{
        	return parameters;
        }
     }   
}  
